<template>
	<view class="container">
		<!-- 页面标题 -->
		<view class="page-title">个性化定制</view>
		
		<!-- 个性化推荐 -->
		<button @click="search" class="recommend">个性化推荐</button>
		
		<!-- 弹出页面 -->
		<view v-if="showModal" class="modal">
		  <view class="modal-content">
		    <span class="close" @click="closeModal">&times;</span>
			<!-- 性别 -->
		    <label>性别</label>
		    <input class="form-input" type="text" v-model="gender" placeholder="请输入" />
			<!--  年龄-->
			<label for="gender">年龄</label>
			<input class="form-input" type="text" v-model="age" placeholder="少年/青年/中年" />
			<!--  场景-->
			<label for="gender">场景需求</label>
			<input class="form-input" type="text" v-model="scene" placeholder="请输入" />
			<!--  寓意-->
			<label for="gender">寓意需求</label>
			<input class="form-input" type="text" v-model="impli" placeholder="请输入" />
			
			<button @click="getRecommend" class="recommend-btn">获取推荐</button>
			
			<view class="recommend-result" v-if="hasRecommendResult">

			  <view v-if="styleList.length" class="result-row">
			    <view class="result-type">款式推荐：</view>
			    <view class="result-tags">
			      <text class="tag" v-for="(item, idx) in styleList" :key="idx">{{ item }}</text>
			    </view>
			  </view>
			  
			  <view v-if="colorList.length" class="result-row">
			    <view class="result-type">颜色推荐：</view>
			    <view class="result-tags">
			      <text class="tag" v-for="(item, idx) in colorList" :key="idx">{{ item }}</text>
			    </view>
			  </view>
			  
			  <view v-if="patternList.length" class="result-row">
			    <view class="result-type">图案推荐：</view>
			    <view class="result-tags">
			      <text class="tag" v-for="(item, idx) in patternList" :key="idx">{{ item }}</text>
			    </view>
			  </view>
			  
			  <view v-if="clothList.length" class="result-row">
			    <view class="result-type">布料推荐：</view>
			    <view class="result-tags">
			      <text class="tag" v-for="(item, idx) in clothList" :key="idx">{{ item }}</text>
			    </view>
			  </view>
			  <button @click="apply" class="recommend">一键生成3d模型</button>
			</view>
		  </view>
		</view>
		
		<!-- 上半部分：DIY区域 -->
		<view class="diy-section">
			<!-- 选项卡 -->
			<view class="diy-tabs">
				<view class="tab-item" :class="{ active: currentTab === 'style' }" @click="this.currentTab = 'style'">
					样式
				</view>
				<view class="tab-item" :class="{ active: currentTab === 'color' }" @click="this.currentTab = 'color'">
					颜色
				</view>
				<view class="tab-item" :class="{ active: currentTab === 'pattern' }"
					@click="this.currentTab = 'pattern'">
					花纹
				</view>
				<view class="tab-item" :class="{ active: currentTab === 'design' }" @click="this.currentTab = 'design'">
					图案
				</view>
				<view class="tab-item" :class="{ active: currentTab === 'fabric' }" @click="this.currentTab = 'fabric'">
					布料
				</view>
			</view>

			<!-- 内容区域 - 根据当前选项卡显示不同内容 -->
			<scroll-view class="diy-content" scroll-y enhanced show-scrollbar>
				<!-- 颜色选择 -->
				<view v-if="currentTab === 'color'" class="content-panel">
					<!-- 主色选择 -->
					<view class="panel-title">主颜色</view>
					<view class="color-options">
						<view class="color-item" :style="{ backgroundColor: color.value }"
							@click="selectOptionWithName('color', color)"
							:class="{ selected: selectedOptions.color === color.value }" v-for="color in colorOptions"
							:key="color.id">
							<view class="check-mark" v-if="selectedOptions.color === color.value">✓</view>
						</view>
					</view>
					<view class="custom-color-input">
						<input type="text" placeholder="自定义十六进制颜色（如#FF0000）" v-model="customColors.color"
							class="color-input" maxlength="7" />
						<button class="confirm-color-btn" @click="setCustomColor('color')">确定</button>
					</view>

					<!-- 副色选择 -->
					<view class="panel-title">副颜色</view>
					<view class="color-options">
						<view class="color-item" :style="{ backgroundColor: color.value }"
							@click="selectOptionWithName('color_1', color)"
							:class="{ selected: selectedOptions.color_1 === color.value }" v-for="color in colorOptions"
							:key="color.id">
							<view class="check-mark" v-if="selectedOptions.color_1 === color.value">✓</view>
						</view>
					</view>
					<view class="custom-color-input">
						<input type="text" placeholder="自定义十六进制颜色（如#FF0000）" v-model="customColors.color_1"
							class="color-input" maxlength="7" />
						<button class="confirm-color-btn" @click="setCustomColor('color_1')">确定</button>
					</view>

					<!-- 辅助色选择 -->
					<view class="panel-title">辅助色</view>
					<view class="color-options">
						<view class="color-item" :style="{ backgroundColor: color.value }"
							@click="selectOptionWithName('color_2', color)"
							:class="{ selected: selectedOptions.color_2 === color.value }" v-for="color in colorOptions"
							:key="color.id">
							<view class="check-mark" v-if="selectedOptions.color_2 === color.value">✓</view>
						</view>
					</view>
					<view class="custom-color-input">
						<input type="text" placeholder="自定义十六进制颜色（如#FF0000）" v-model="customColors.color_2"
							class="color-input" maxlength="7" />
						<button class="confirm-color-btn" @click="setCustomColor('color_2')">确定</button>
					</view>
				</view>

				<!-- 样式选择 -->
				<view v-else-if="currentTab === 'style'" class="content-panel">
					<view class="panel-title">选择样式</view>
					<view class="style-options">
						<view class="style-item" @click="selectOptionWithName('style', style)"
							:class="{ selected: selectedOptions.style === style.value }" v-for="style in styleOptions"
							:key="style.id">
							<image :src="style.imgUrl" mode="widthFix" class="style-img"></image>
							<view class="style-name">{{ style.name }}</view>
						</view>
					</view>
				</view>

				<!-- 花纹选择 -->
				<view v-else-if="currentTab === 'pattern'" class="content-panel">
					<view class="panel-title">选择花纹</view>
					<view class="pattern-options">
						<view class="pattern-item" @click="selectOptionWithName('pattern', pattern)"
							:class="{ selected: selectedOptions.pattern === pattern.value }"
							v-for="pattern in patternOptions" :key="pattern.id">
							<image :src="pattern.imgUrl" mode="widthFix" class="pattern-img"></image>
							<view class="pattern-name">{{ pattern.name }}</view>
						</view>
					</view>
					<!-- 花纹自定义URL输入 -->
					<view class="custom-color-input">
						<input type="text" placeholder="输入花纹图片URL" v-model="customPatternUrl" class="color-input" />
						<button class="confirm-color-btn" @click="setCustomUrl('pattern')">确定</button>
					</view>
				</view>

				<!-- 图案选择 -->
				<view v-else-if="currentTab === 'design'" class="content-panel">
					<view class="panel-title">选择图案</view>
					<view class="design-options">
						<view class="design-item" @click="selectOptionWithName('design', design)"
							:class="{ selected: selectedOptions.design === design.value }"
							v-for="design in designOptions" :key="design.id">
							<image :src="design.imgUrl" mode="widthFix" class="design-img"></image>
							<view class="design-name">{{ design.name }}</view>
						</view>
					</view>
					<!-- 图案自定义URL输入 -->
					<view class="custom-color-input">
						<input type="text" placeholder="输入图案图片URL" v-model="customDesignUrl" class="color-input" />
						<button class="confirm-color-btn" @click="setCustomUrl('design')">确定</button>
					</view>
				</view>

				<!-- 布料选择 -->
				<view v-else-if="currentTab === 'fabric'" class="content-panel">
					<view class="panel-title">选择布料</view>
					<view class="fabric-options">
						<view class="fabric-item" @click="selectOptionWithName('fabric', fabric)"
							:class="{ selected: selectedOptions.fabric === fabric.value }"
							v-for="fabric in fabricOptions" :key="fabric.id">
							<view class="fabric-marker"></view>
							<view class="fabric-text">
								<view class="fabric-name">{{ fabric.name }}</view>
								<view class="fabric-desc">{{ fabric.desc }}</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 下半部分：3D展示区域 -->
		<view class="preview-section">
			<view class="preview-title">3D 预览</view>
			<view class="preview-content">
				<view class="selection-info">
					<view class="color-info-row">
						<view class="info-item color-info-item">主色:
							{{ selectedOptions.colorName || selectedOptions.color || '未选择' }}
						</view>
						<view class="info-item color-info-item">副色:
							{{ selectedOptions.color_1Name || selectedOptions.color_1 || '未选择' }}
						</view>
						<view class="info-item color-info-item">辅助色:
							{{ selectedOptions.color_2Name || selectedOptions.color_2 || '未选择' }}
						</view>
					</view>
					<view class="info-item">样式: {{ selectedOptions.styleName || '未选择' }}</view>
					<view class="info-item">花纹: {{ selectedOptions.patternName || '未选择' }}</view>
					<view class="info-item">图案: {{ selectedOptions.designName || '未选择' }}</view>
					<view class="info-item">布料: {{ selectedOptions.fabricName || '未选择' }}</view>
				</view>
			</view>
			<HanFu :color="selectedOptions.color" :color_1="selectedOptions.color_1" :color_2="selectedOptions.color_2"
				:style="selectedOptions.style" :pattern="selectedOptions.pattern" :design="selectedOptions.design"
				:fabric="selectedOptions.fabric"></HanFu>
			<!-- 确认按钮 -->
			<button class="confirm-btn" @click="saveHanfu">确认选择</button>
		</view>
	</view>
</template>

<script>
	import hanfuVue from '../../components/HanFu.vue';
	export default {
		components: {
			HanFu: hanfuVue
		},
		onShow() {
		  // 只有存在参数时才解析
		  const paramsStr = uni.getStorageSync('hanfuCustomParams');
		  if (paramsStr) { // 当存在参数（非空）时才执行解析
		    try {
		      const customParams = JSON.parse(paramsStr);
		      this.selectedOptions = { ...this.selectedOptions, ...customParams };
		      console.log("正确解析的参数：", this.selectedOptions);
		    } catch (error) {
		      console.error("参数解析失败：", error);
		      uni.showToast({ title: '参数格式错误', icon: 'none' });
		    }
		    // 清除本地存储（无论解析成功与否都清除，避免残留）
		    uni.removeStorageSync('hanfuCustomParams');
		  } else {
		    // 可选：当没有参数时的处理（如使用默认值）
		    console.log("没有获取到定制参数，使用默认值");
		  }
		},
		data() {
			return {
				//推荐模拟框
				showModal:false,
				gender: '',//性别
				age: '',//年龄   
				scene: '' ,//场景
				impli: '',//寓意
				styleList: [],   // 储存结果
				colorList: [],  
				patternList: [], 
				clothList: [],
				
				// 当前选中的选项卡
				currentTab: 'style',

				// 选中的选项
				selectedOptions: {
					userId: 1,
					color: '#FFFFFF', // 主色
					colorName: '白色',
					color_1: '#FFB61E', // 副色
					color_1Name: '黄色',
					color_2: '#FF0000', // 辅助色
					color_2Name: '红色',
					style: 'https://hub.gitmirror.com/https://raw.githubusercontent.com/zhang666jl/data/refs/heads/main/chest_height.glb',
					styleName: '齐胸襦裙',
					pattern: '',
					patternName: '',
					design: '',
					designName: '',
					fabric: '',
					fabricName: ''
				},

				// 颜色选项
				colorOptions: [{
						id: 1,
						value: '#000000',
						name: '黑色'
					},
					{
						id: 2,
						value: '#FFFFFF',
						name: '白色'
					},
					{
						id: 3,
						value: '#FF0000',
						name: '红色'
					},
					{
						id: 4,
						value: '#4B5CC4',
						name: '蓝色'
					},
					{
						id: 5,
						value: '#41B349',
						name: '绿色'
					},
					{
						id: 6,
						value: '#FFB61E',
						name: '黄色'
					},
					{
						id: 7,
						value: '#FFA500',
						name: '橙色'
					},
					{
						id: 8,
						value: '#8D4BBB',
						name: '紫色'
					}
				],

				// 样式选项
				styleOptions: [{
						id: 1,
						name: '齐胸襦裙',
						value: 'https://hub.gitmirror.com/https://raw.githubusercontent.com/zhang666jl/data/refs/heads/main/chest_height.glb',
						imgUrl: '/static/3d/齐胸襦裙.png'
					},
					{
						id: 2,
						name: '交领宽袍',
						value: 'https://hub.gitmirror.com/https://raw.githubusercontent.com/zhang666jl/data/refs/heads/main/test.glb',
						imgUrl: '/static/3d/交领宽袍.png'
					},
					{
						id: 3,
						name: '对襟外衫襦裙',
						value: 'https://hub.gitmirror.com/https://raw.githubusercontent.com/zhang666jl/data/refs/heads/main/outside.glb?1',
						imgUrl: '/static/3d/对襟外衫襦裙.png'
					},
					{
						id: 4,
						name: '圆领袍',
						value: 'https://hub.gitmirror.com/https://raw.githubusercontent.com/zhang666jl/data/refs/heads/main/man.glb',
						imgUrl: '/static/3d/圆领袍.png'
					}
				],

				// 花纹选项
				patternOptions: [{
						id: 1,
						name: '云纹',
						value: 'https://s21.ax1x.com/2025/08/24/pVsLezT.jpg',
						imgUrl: 'https://s21.ax1x.com/2025/08/24/pVsLezT.jpg'
					},
					{
						id: 2,
						name: '牡丹',
						value: 'https://s21.ax1x.com/2025/08/24/pVsLFds.jpg',
						imgUrl: 'https://s21.ax1x.com/2025/08/24/pVsLFds.jpg'
					},
					{
						id: 3,
						name: '水纹',
						value: 'https://s21.ax1x.com/2025/08/24/pVsLEiq.jpg',
						imgUrl: 'https://s21.ax1x.com/2025/08/24/pVsLEiq.jpg'
					}
				],

				// 图案选项
				designOptions: [{
						id: 1,
						name: '龙',
						value: 'https://s21.ax1x.com/2025/08/24/pVsLkon.jpg',
						imgUrl: 'https://s21.ax1x.com/2025/08/24/pVsLkon.jpg'
					},
					{
						id: 2,
						name: '凤',
						value: 'https://s21.ax1x.com/2025/08/24/pVsLVJ0.jpg',
						imgUrl: 'https://s21.ax1x.com/2025/08/24/pVsLVJ0.jpg'
					},
					{
						id: 3,
						name: '荷花',
						value: 'https://s21.ax1x.com/2025/08/24/pVsLZWV.jpg',
						imgUrl: 'https://s21.ax1x.com/2025/08/24/pVsLZWV.jpg'
					}
				],

				// 布料选项
				fabricOptions: [{
						id: 1,
						name: '纯棉',
						value: 'cotton',
						desc: '透气舒适'
					},
					{
						id: 2,
						name: '羊毛',
						value: 'wool',
						desc: '保暖性好'
					},
					{
						id: 3,
						name: '丝绸',
						value: 'silk',
						desc: '光滑柔软'
					},
					{
						id: 4,
						name: '涤纶',
						value: 'polyester',
						desc: '耐磨耐用'
					}
				],
				customColors: {
					color: '', // 主色自定义输入
					color_1: '', // 副色自定义输入
					color_2: '' // 辅助色自定义输入
				},
				customPatternUrl: '', 
				customDesignUrl: ''
			};
		},
		computed: {
		  hasRecommendResult() {
		    return this.styleList.length || this.colorList.length || this.patternList.length || this.clothList.length;
		  }
		},
		methods: {
			//推荐页面
			search() {
			    this.showModal = true;
			},
			closeModal() {
			  this.showModal = false;
			},
			clearRecommendLists() {
			      this.styleList = [];
			      this.colorList = [];
			      this.patternList = [];
			      this.clothList = [];
			    },
			getRecommend() {
			      const inputs = {
			        gender: this.gender.trim(),
			        age: this.age.trim(),
			        scene: this.scene.trim(),
			        impli: this.impli.trim()
			      };
			      const emptyFields = Object.entries(inputs)
			        .filter(([k, v]) => !v)
			        .map(([k]) => ({ gender: '性别', age: '年龄', scene: '场景', impli: '寓意' }[k]));
			      if (emptyFields.length) {
			        uni.showToast({ title: `请填写：${emptyFields.join('、')}`, icon: 'none' });
			        return;
			      }
			
			      const knowledgeGraph = {
			        "男性": ["交领宽袍（款式）", "圆领袍（款式）", "黑色（颜色）", "青色（颜色）", "龙纹（图案）", "云纹（图案）", "羊毛（面料）", "丝绸（面料）"],
			        "女性": ["齐胸襦裙（款式）", "对襟外衫襦裙（款式）", "赤色（颜色）", "粉色（颜色）", "牡丹（图案）", "荷花（图案）", "丝绸（面料）", "纯棉（面料）"],
			        "少年": ["对襟外衫襦裙（款式）", "粉色（颜色）", "橙色（颜色）", "云纹（图案）", "荷花（图案）", "纯棉（面料）", "涤纶（面料）"],
			        "青年": ["齐胸襦裙（款式）", "交领宽袍（款式）", "赤色（颜色）", "青色（颜色）", "牡丹（图案）", "水纹（图案）", "丝绸（面料）", "纯棉（面料）"],
			        "中年": ["交领宽袍（款式）", "圆领袍（款式）", "黑色（颜色）", "白色（颜色）", "龙纹（图案）", "云纹（图案）", "羊毛（面料）", "丝绸（面料）"],
			        "婚礼": ["齐胸襦裙（款式）", "对襟外衫襦裙（款式）", "赤色（颜色）", "粉色（颜色）", "凤纹（图案）", "牡丹（图案）", "丝绸（面料）"],
			        "庆典": ["交领宽袍（款式）", "圆领袍（款式）", "黄色（颜色）", "赤色（颜色）", "龙纹（图案）", "牡丹（图案）", "丝绸（面料）", "羊毛（面料）"],
			        "日常": ["对襟外衫襦裙（款式）", "交领宽袍（款式）", "白色（颜色）", "青色（颜色）", "云纹（图案）", "水纹（图案）", "纯棉（面料）", "涤纶（面料）"],
			        "丧葬": ["交领宽袍（款式）", "圆领袍（款式）", "黑色（颜色）", "白色（颜色）", "无图案（简约）", "纯棉（面料）", "涤纶（面料）"],
			        "祭祀": ["交领宽袍（款式）", "圆领袍（款式）", "黑色（颜色）", "青色（颜色）", "云纹（图案）", "龙纹（图案）", "丝绸（面料）", "羊毛（面料）"],
			        "吉祥": ["赤色（颜色）", "黄色（颜色）", "龙纹（图案）", "凤纹（图案）", "牡丹（图案）", "丝绸（面料）"],
			        "喜庆": ["赤色（颜色）", "粉色（颜色）", "牡丹（图案）", "凤纹（图案）", "荷花（图案）", "丝绸（面料）"],
			        "庄重": ["黑色（颜色）", "青色（颜色）", "云纹（图案）", "龙纹（图案）", "丝绸（面料）", "羊毛（面料）"],
			        "纯洁": ["白色（颜色）", "粉色（颜色）", "荷花（图案）", "水纹（图案）", "纯棉（面料）", "丝绸（面料）"],
			        "素雅": ["白色（颜色）", "青色（颜色）", "云纹（图案）", "水纹（图案）", "纯棉（面料）", "涤纶（面料）"],
			        "清新": ["青色（颜色）", "粉色（颜色）", "荷花（图案）", "水纹（图案）", "纯棉（面料）", "丝绸（面料）"],
			        "活泼": ["橙色（颜色）", "粉色（颜色）", "云纹（图案）", "荷花（图案）", "纯棉（面料）", "涤纶（面料）"]
			      };
			
			      const rawRecommend = this.alternatingLearning(inputs, knowledgeGraph);
			      
			      this.classifyRecommendResult(rawRecommend);
			    },
			classifyRecommendResult(rawList) {

			      this.clearRecommendLists();
			      
			      rawList.forEach(item => {
			        if (item.includes('（款式）')&& this.styleList.length < 2) {
			          const styleName = item.replace('（款式）', '');
			          this.styleList.push(styleName);
			        } else if (item.includes('（颜色）')&& this.colorList.length < 2) {
			          const colorName = item.replace('（颜色）', '');
			          this.colorList.push(colorName);
			        } else if (item.includes('（图案）')&& this.patternList.length < 2) {
			          const patternName = item.replace('（图案）', '');
			          this.patternList.push(patternName);
			        } else if (item.includes('（面料）')&& this.clothList.length < 2) {
			          const clothName = item.replace('（面料）', '');
			          this.clothList.push(clothName);
			        }
			      });
			    },
			
			    alternatingLearning(inputs, knowledgeGraph) {
			      const groupA = ['gender', 'age'];
			      const groupB = ['scene', 'impli'];
			      let weights = { gender: 1, age: 1, scene: 1, impli: 1 };
			      const iterations = 3;

			      for (let i = 0; i < iterations; i++) {
			        weights = this.optimizeWeights(groupA, groupB, inputs, weights, knowledgeGraph);
			        weights = this.optimizeWeights(groupB, groupA, inputs, weights, knowledgeGraph);
			      }
			
			      const resultMap = {};
			      Object.entries(inputs).forEach(([key, value]) => {
			        if (knowledgeGraph[value]) {
			          knowledgeGraph[value].forEach(tag => {
			            resultMap[tag] = (resultMap[tag] || 0) + weights[key];
			          });
			        }
			      });

			      return Object.entries(resultMap)
			        .sort((a, b) => b[1] - a[1])
			        .map(([tag]) => tag)
			        .slice(0, 12); 
			    },
			
			    optimizeWeights(targetGroup, referenceGroup, inputs, weights, knowledgeGraph) {
			      let refScore = 0;
			      referenceGroup.forEach(key => {
			        const value = inputs[key];
			        if (knowledgeGraph[value]) refScore += knowledgeGraph[value].length * weights[key];
			      });
			
			      const newWeights = { ...weights };
			      targetGroup.forEach(key => {
			        const value = inputs[key];
			        if (knowledgeGraph[value]) {
			          newWeights[key] = refScore > 0 
			            ? Math.max(0.5, weights[key] * (5 / refScore)) 
			            : weights[key] * 1.2;
			        }
			      });
			      return newWeights;
			    },
			apply() {
			  // 颜色映射：将颜色名称转换为颜色值
			  const colorMap = {
			    '黑色': '#000000',
			    '白色': '#FFFFFF', 
			    '红色': '#FF0000',
			    '蓝色': '#4B5CC4',
			    '绿色': '#41B349',
			    '黄色': '#FFB61E',
			    '橙色': '#FFA500',
			    '紫色': '#8D4BBB',
			    '赤色': '#FF0000',
			    '青色': '#41B349',
			    '粉色': '#FFC0CB'
			  };
			  
			  // 样式映射：将样式名称转换为模型URL
			  const styleMap = {
			    '齐胸襦裙': 'https://hub.gitmirror.com/https://raw.githubusercontent.com/zhang666jl/data/refs/heads/main/chest_height.glb',
			    '交领宽袍': 'https://hub.gitmirror.com/https://raw.githubusercontent.com/zhang666jl/data/refs/heads/main/test.glb',
			    '对襟外衫襦裙': 'https://hub.gitmirror.com/https://raw.githubusercontent.com/zhang666jl/data/refs/heads/main/outside.glb?1',
			    '圆领袍': 'https://hub.gitmirror.com/https://raw.githubusercontent.com/zhang666jl/data/refs/heads/main/man.glb'
			  };
			  
			  // 图案映射：将图案名称转换为图片URL
			  const patternMap = {
			    '云纹': 'https://s21.ax1x.com/2025/08/24/pVsLezT.jpg',
			    '牡丹': 'https://s21.ax1x.com/2025/08/24/pVsLFds.jpg',
			    '水纹': 'https://s21.ax1x.com/2025/08/24/pVsLEiq.jpg',
			    '龙纹': 'https://s21.ax1x.com/2025/08/24/pVsLkon.jpg',
			    '凤纹': 'https://s21.ax1x.com/2025/08/24/pVsLVJ0.jpg',
			    '荷花': 'https://s21.ax1x.com/2025/08/24/pVsLZWV.jpg'
			  };
			  
			  // 布料映射
			  const fabricMap = {
			    '纯棉': 'cotton',
			    '羊毛': 'wool', 
			    '丝绸': 'silk',
			    '涤纶': 'polyester'
			  };
			
			  // 应用推荐结果（只应用存在的推荐项）
			  if (this.colorList.length > 0) {
			    const colorName = this.colorList[0];
			    this.selectedOptions.color = colorMap[colorName] || '#FFFFFF';
			    this.selectedOptions.colorName = colorName;
			  }
			  
			  if (this.colorList.length > 1) {
			    const color1Name = this.colorList[1];
			    this.selectedOptions.color_1 = colorMap[color1Name] || '#FFB61E';
			    this.selectedOptions.color_1Name = color1Name;
			  }
			  
			  if (this.styleList.length > 0) {
			    const styleName = this.styleList[0];
			    this.selectedOptions.style = styleMap[styleName] || this.styleOptions[0].value;
			    this.selectedOptions.styleName = styleName;
			  }
			  
			  if (this.patternList.length > 0) {
			    const patternName = this.patternList[0];
			    this.selectedOptions.pattern = patternMap[patternName] || '';
			    this.selectedOptions.patternName = patternName;
			  }
			  
			  if (this.clothList.length > 0) {
			    const fabricName = this.clothList[0];
			    this.selectedOptions.fabric = fabricMap[fabricName] || '';
			    this.selectedOptions.fabricName = fabricName;
			  }
			  
			  // 关闭弹窗
			  this.showModal = false;
			  
			  uni.showToast({
			    title: '推荐配置已应用',
			    icon: 'success'
			  });
			},
			// 选择选项
			selectOptionWithName(type, option) {
				// 设置值
				this.selectedOptions[type] = option.value;
				// 设置名称
				this.selectedOptions[`${type}Name`] = option.name;
			},
			setCustomColor(type) {
				// 获取对应颜色类型的输入值
				const colorInput = this.customColors[type];

				// 验证输入不为空
				if (!colorInput) {
					uni.showToast({
						title: '请输入颜色值',
						icon: 'none'
					});
					return;
				}

				// 验证十六进制颜色格式（支持#开头和6位/3位格式）
				const hexReg = /^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;
				if (!hexReg.test(colorInput)) {
					uni.showToast({
						title: '请输入有效的十六进制颜色',
						icon: 'none'
					});
					return;
				}

				// 统一格式（确保以#开头）
				const colorValue = colorInput.startsWith('#') ?
					colorInput :
					`#${colorInput}`;

				// 根据颜色类型更新对应的值和名称
				this.selectedOptions[type] = colorValue;
				this.selectedOptions[`${type}Name`] = colorValue;

				// 清空对应输入框
				this.customColors[type] = '';

				// 提示成功
				uni.showToast({
					title: `${type}设置成功`,
					icon: 'success'
				});
			},
			setCustomUrl(type) {
				// 获取对应类型的输入值
				const urlInput = type === 'pattern' ? this.customPatternUrl : this.customDesignUrl;

				// 验证输入不为空
				if (!urlInput.trim()) {
					uni.showToast({
						title: `请输入${type === 'pattern' ? '花纹' : '图案'}图片URL`,
						icon: 'none'
					});
					return;
				}

				// 简单验证URL格式（判断是否包含http/https和图片扩展名）
				const urlReg = /^(https?:\/\/).*\.(jpg|jpeg|png|gif|bmp|webp)$/i;
				if (!urlReg.test(urlInput)) {
					uni.showToast({
						title: '请输入有效的图片URL（需以http开头且包含图片扩展名）',
						icon: 'none'
					});
					return;
				}

				// 更新选中的选项值和名称
				this.selectedOptions[type] = urlInput; // 存储URL作为值
				this.selectedOptions[`${type}Name`] = urlInput; // 显示名称

				// 清空对应输入框
				if (type === 'pattern') {
					this.customPatternUrl = '';
				} else {
					this.customDesignUrl = '';
				}

				// 提示成功
				uni.showToast({
					title: `${type === 'pattern' ? '花纹' : '图案'}设置成功`,
					icon: 'success'
				});
			},
			async saveHanfu() {
			    try {
			      // 1. 转换参数格式（下划线转驼峰，适配后端实体类）
			      const requestData = {
			        userId: this.selectedOptions.userId, // 用户ID
			        color: this.selectedOptions.color,
			        colorName: this.selectedOptions.colorName,
			        color1: this.selectedOptions.color_1, // 前端color_1 → 后端color1
			        color1Name: this.selectedOptions.color_1Name,
			        color2: this.selectedOptions.color_2, // 前端color_2 → 后端color2
			        color2Name: this.selectedOptions.color_2Name,
			        style: this.selectedOptions.style,
			        styleName: this.selectedOptions.styleName,
			        pattern: this.selectedOptions.pattern,
			        patternName: this.selectedOptions.patternName,
			        design: this.selectedOptions.design,
			        designName: this.selectedOptions.designName,
			        fabric: this.selectedOptions.fabric,
			        fabricName: this.selectedOptions.fabricName
			      };
			
			      const res = await uni.$http.post('/hanfu/save', requestData);
			      // 3. 处理响应结果
			      if (res.statusCode !== 200) {
			        throw new Error(`请求失败，状态码：${res.statusCode}`);
			      }
			
			      if (res.data.code === 1) {
			        uni.showToast({
			          title: '保存成功',
			          icon: 'success',
			          duration: 1500
			        });
			        console.log('保存成功');
			      } else {
			        uni.showToast({
			          title: res.data.message || '保存失败',
			          icon: 'none',
			          duration: 1500
			        });
			      }
			
			    } catch (error) {
			      // 4. 错误处理
			      console.error('保存失败：', error);
			      uni.showToast({
			        title: '网络错误，请稍后重试',
			        icon: 'none',
			        duration: 1500
			      });
			    }
			  }
		}
	};
</script>

<style scoped>
	/* 个性化推荐 */
	.recommend {
		width: 90%;
		height: 88rpx;
		line-height: 88rpx; 
		margin: 30rpx auto;
		background-color: #8b5a2b;
		color: #f5f0e6; 
		border-color: black;
		border-radius: 44rpx; 
		font-size: 28rpx; 
		font-weight: 500;
		letter-spacing: 2rpx;  
	}
	
	.modal {
	  position: fixed;
	  top: 0;
	  left: 0;
	  width: 100vw;
	  height: 100vh;
	  background-color: rgba(0, 0, 0, 0.5); 
	  z-index: 999;
	  display: flex;
	  justify-content: center;
	  align-items: center;
	  padding: 20px; 
	  box-sizing: border-box;
	}
	
	.modal-content {
	  width: 100%;
	  max-width: 320px; 
	  background-color: #FFFAE8;
	  border-radius: 12px; 
	  padding: 28px 24px;
	  position: relative; 
	}
	
	.close {
	  position: absolute;
	  top: 16px;
	  right: 16px;
	  font-size: 22px;
	  color: #999;
	  transition: color 0.2s ease;
	}
	
	.form-input {
	  display: block; 
	  margin-top: 18px; 
	  margin-bottom: 8px; 
	  font-size: 15px;
	  color: #333;
	  font-weight: 500; 
	}
	.form-input:first-of-type {
	  margin-top: 0;
	}
	
	.form-input {
	  width: 100%;
	  height: 40px;
	  padding: 0 14px;
	  border: 1px solid #e5e5e5; 
	  border-radius: 8px;
	  font-size: 16px;
	  color: #333;
	  box-sizing: border-box;
	}
	.form-input::placeholder {
	  color: #ccc;
	  font-size: 15px;
	}
	.recommend-btn {
	  width: 100%;
	  height: 40px;
	  margin-top: 20px; 
	  background-color: #8b5a2b; 
	  color: #fff;
	  border-radius: 8px;
	  font-size: 16px;
	}
	.recommend-result {
	  margin-top: 24px;
	}
	/* 推荐结果 */
	.result-row {
	  display: flex;
	  align-items: center;
	  margin-bottom: 10px;
	  flex-wrap: wrap; 
	}
	
	.result-type {
	  font-size: 15px;
	  font-weight: bold;
	  color: #8b5a2b;
	  margin-right: 8px;
	  white-space: nowrap; 
	}
	
	.result-tags {
	  display: flex;
	  flex-wrap: wrap;
	  gap: 8px; 
	  flex: 1; 
	}
	
	.tag {
	  background-color: #f5f0e6;
	  color: #8b5a2b;
	  padding: 4px 8px;
	  border-radius: 4px;
	  font-size: 14px;
	}
	
	
	.container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background-color: #f8f5f0;
	}

	.page-title {
		padding: 20rpx 0;
		text-align: center;
		font-size: 36rpx;
		font-weight: bold;
		background-color: #8b5a2b;
		color: #f5f0e6;
		border-bottom: 1px solid #a67c52;
	}

	/* DIY区域样式 */
	.diy-section {
		flex: 1;
		padding: 20rpx;
		background-color: #f5f0e6;
		margin: 10rpx;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(139, 90, 43, 0.1);
	}

	/* 选项卡样式 */
	.diy-tabs {
		display: flex;
		overflow-x: auto;
		padding-bottom: 10rpx;
		border-bottom: 1px solid #d9c9b8;
		margin-bottom: 20rpx;
	}

	.tab-item {
		padding: 15rpx 30rpx;
		font-size: 28rpx;
		white-space: nowrap;
		margin-right: 10rpx;
		border-radius: 20rpx;
	}

	.tab-item.active {
		background-color: #8b5a2b;
		color: #f5f0e6;
	}

	/* 内容面板样式 */
	.diy-content {
		height: calc(100vh * 0.2);
		padding: 10rpx;
	}

	.content-panel {
		padding: 10rpx;
	}

	.panel-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		color: #5c3d1f;
	}

	/* 颜色选项样式 */
	.color-options {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.color-item {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		position: relative;
		transition: transform 0.2s;
	}


	.color-item.selected {
		transform: scale(1.1);
		box-shadow: 0 0 0 2px #f5f0e6, 0 0 0 4px #8b5a2b;
	}

	.check-mark {
		position: absolute;
		color: white;
		font-weight: bold;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
	}

	/* 样式选项样式 */
	.style-options,
	.pattern-options,
	.design-options,
	.fabric-options {
		display: flex;
		flex-wrap: wrap;
		gap: 15rpx;
	}

	.style-item,
	.pattern-item,
	.design-item,
	.fabric-item {
		width: 160rpx;
		padding: 15rpx;
		border-radius: 10rpx;
		border: 1px solid #eeeeee;
		text-align: center;
		cursor: pointer;
		transition: all 0.2s;
	}

	.style-item.selected,
	.pattern-item.selected,
	.design-item.selected,
	.fabric-item.selected {
		border-color: #8b5a2b;
		background-color: rgba(139, 90, 43, 0.05);
	}

	.style-img,
	.pattern-img,
	.design-img {
		width: 120rpx;
		height: 120rpx;
		margin: 0 auto 10rpx;
		border-radius: 5rpx;
	}

	/* 左侧装饰标记 */
	.fabric-marker {
		width: 12rpx;
		height: 12rpx;
		border-radius: 50%;
		background-color: #8b5a2b;
		margin-right: 20rpx;
	}

	/* 文字区域 */
	.fabric-text {
		flex: 1;
		/* 占满剩余空间 */
	}

	.style-name,
	.pattern-name,
	.design-name,
	.fabric-name {
		font-size: 26rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.fabric-desc {
		font-size: 20rpx;
		color: #999999;
		margin-top: 5rpx;
	}

	/* 预览区域样式 */
	.preview-section {
		flex: 2;
		padding: 20rpx;
		background-color: #f5f0e6;
		border-top: 1px solid #d9c9b8;
	}

	.preview-title {
		font-size: 30rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		color: #5c3d1f;
		text-align: center;
	}

	.preview-content {
		min-height: 200rpx;
		background-color: #f8f5f0;
		border-radius: 10rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
	}

	.selection-info {
		display: flex;
		flex-direction: column;
		gap: 10rpx;
	}

	.info-item {
		text-align: center;
		font-size: 26rpx;
		color: #5c3d1f;
	}

	.confirm-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 30rpx;
		background-color: #8b5a2b;
		color: #ffffff;
		border-radius: 40rpx;
	}

	.color-group {
		margin-bottom: 30rpx;
	}

	.group-title {
		font-size: 28rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
		color: #5c3d1f;
	}

	/* 新增颜色行布局样式 */
	.color-info-row {
		display: flex;
		width: 100%;
		justify-content: space-between;
		/* 均匀分布 */
		gap: 10rpx;
		/* 间距 */
		margin-bottom: 10rpx;
		/* 与下方选项分隔 */
	}

	/* 颜色项样式 */
	.color-info-item {
		flex: 1;
		/* 平均分配宽度 */
		text-align: center;
		/* 文字居中 */
		white-space: nowrap;
		/* 防止换行 */
		overflow: hidden;
		/* 超出隐藏 */
		text-overflow: ellipsis;
		/* 省略号显示 */
	}

	/* 自定义颜色输入区域样式 */
	.custom-color-input {
		display: flex;
		gap: 15rpx;
		margin-bottom: 25rpx;
		align-items: center;
		padding: 0 10rpx;
	}

	.color-input {
		flex: 1;
		height: 60rpx;
		padding: 0 15rpx;
		border: 1px solid #d9c9b8;
		border-radius: 6rpx;
		font-size: 24rpx;
		color: #5c3d1f;
		background-color: #f8f5f0;
	}

	/* 确认按钮样式 */
	.confirm-color-btn {
		min-width: 120rpx;
		height: 60rpx;
		line-height: 60rpx;
		padding: 0 20rpx;
		font-size: 24rpx;
		background-color: #8b5a2b;
		color: #ffffff;
		border-radius: 6rpx;
		white-space: nowrap;
	}

	/* 增加颜色选项区域的间距 */
	.color-options {
		margin-bottom: 30rpx;
	}
</style>
